package com.gxuwz.endrskyweather.viewmodel;

import android.app.Application;
import androidx.lifecycle.AndroidViewModel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import com.gxuwz.endrskyweather.model.City;
import com.gxuwz.endrskyweather.repository.CityRepository;
import java.util.List;

public class AddCityViewModel extends AndroidViewModel {
    private CityRepository repository;
    private MutableLiveData<List<City>> cities = new MutableLiveData<>();

    public AddCityViewModel(Application application) {
        super(application);
        repository = new CityRepository(application);
        loadCities();
    }

    public LiveData<List<City>> getCities() {
        return cities;
    }

    private void loadCities() {
        new Thread(() -> {
            List<City> cityList = repository.getAllCities();
            cities.postValue(cityList);
        }).start();
    }

    public void searchCities(String query) {
        new Thread(() -> {
            List<City> results;
            if (query.matches("\\d+")) {
                // 数字搜索城市代码
                results = repository.searchCitiesByCode(query);
            } else {
                // 文字搜索城市名
                results = repository.searchCitiesByName(query);
            }
            cities.postValue(results);
        }).start();
    }

    public void refreshCities() {
        loadCities();
    }
}
